<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/23/023
 * Time: 10:15
 */

namespace app\api\service;


use app\lib\exception\TokenException;
use think\Exception;
use think\facade\Cache;
use think\facade\Request;

class Token {

    /**
     * 创建token令牌方法
     * @return string
     */
    public static function generateToken()
    {
        //32个字符组成一组随机字符串
        $randChars = getRandChar(32);
        //用三组字符串，进行md5加密
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        //salt 盐
        $salt = getRandChar(32);

        return md5($randChars . $timestamp . $salt);
    }

    /**
     * 获取token下面的某个值
     * @param $key
     * @return mixed
     * @throws Exception
     * @throws TokenException
     */
    public static function getCurrentTokenVar($key)
    {
        $token = Request::header('token');
        if (!$token) {
            throw new TokenException([
                'msg' => '请添加用户token'
            ]);
        }
        $vars = Cache::get($token, '');
        if (!$vars)
        {
            throw new TokenException();
        }
        else
        {
            if (!is_array($vars))
            {
                $vars = json_decode($vars, true);
            }
            if (array_key_exists($key, $vars))
            {
                 // 重置token数据
                $expire_in = config('setting.member_token_expire_in');
                $request = cache($token, $vars, $expire_in);
                if(!$request){
                    throw new TokenException([
                        'msg' => '重置token缓存信息异常',
                        'errorCode' => 40002
                    ]);
                }
                return $vars[$key];
            }
            else
            {
                throw new Exception('尝试获取的Token变量并不存在');
            }
        }
    }

    /**
     * 获取uid
     * @return mixed
     */
    public static function getCurrentUid()
    {
        //token
        $uid = self::getCurrentTokenVar('member_id');
        return $uid;
    }
}